package top.tenebrous.yzl.chat.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.tenebrous.yzl.basic.exceptions.BizException;
import top.tenebrous.yzl.chat.annotation.NoAuthority;
import top.tenebrous.yzl.chat.constants.RedisKeyConstants;
import top.tenebrous.yzl.chat.model.MemberLoginInfo;
import top.tenebrous.yzl.chat.utils.ThreadLocalUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Author qzcha
 * @Date 2023/3/23 10:20
 * @Version 1.0
 */
@Slf4j
@Component
public class IMHeaderInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${sa-token.token-prefix}")
    private String tokenPrefix;

    @Value("${sa-token.token-name}")
    private String tokenName;

    public IMHeaderInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取拦截的方法
            Method method = handlerMethod.getMethod();
            NoAuthority annotation = method.getAnnotation(NoAuthority.class);
            log.info("拦截器前置校验:获取鉴权注解:{}", JSON.toJSONString(annotation));
            if (Objects.nonNull(annotation)) {
                log.info("拦截器前置校验:方法:[{}]存在@NoAuthority注解:无需校验token", method.getName());
                return true;
            }
            log.info("拦截器前置校验:方法:[{}]不存在@NoAuthority注解:需要校验token", method.getName());
        }

        HttpHeaders headers = (new ServletServerHttpRequest(request)).getHeaders();
        String token = headers.getFirst(tokenName);
        log.info("拦截器启动:请求token:{}", token);
        if (StrUtil.isNotBlank(token)) {
            log.info("拦截器拦截：获取tokenPrefix:{}", tokenPrefix);
            token = token.replace(tokenPrefix, "").trim();
            log.info("拦截器拦截：截取后token:{}", token);
            String redisKey = String.format(RedisKeyConstants.TOKEN, token);
            log.info("拦截器启动:redis key:{}", redisKey);
            String info = stringRedisTemplate.opsForValue().get(redisKey);
            log.info("拦截器启动:redis value:{}", info);
            if (StringUtils.isBlank(info)) {
                throw new BizException("非法访问");
            }
            MemberLoginInfo memberInfo = JSON.parseObject(info, MemberLoginInfo.class);
            ThreadLocalUtil.put("userInfo", memberInfo);
        } else {
           throw new BizException("当前用户未登录");
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.clear();
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ThreadLocalUtil.clear();
    }
}
